package platform

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	hlpaymodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/models"
	hlservices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonmodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	photonpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"gorm.io/gorm"
)

// CardListController 统一的卡列表控制器
// 根据用户的平台类型自动选择对应的平台进行卡列表查询
type CardListController struct {
	photonpayClient   *photonpay.PhotonPayClient
	hlpayClient       *hlPay.HlPayClient
	statisticsService *service.StatisticsService
	db                *gorm.DB
	// 添加互斥锁避免并发冲突
	mu sync.RWMutex
}

// NewCardListController 创建卡列表控制器实例
func NewCardListController(photonpayClient *photonpay.PhotonPayClient, hlpayClient *hlPay.HlPayClient, db *gorm.DB) *CardListController {
	return &CardListController{
		photonpayClient:   photonpayClient,
		hlpayClient:       hlpayClient,
		statisticsService: service.NewStatisticsService(photonpayClient),
		db:                db,
	}
}

// GetCardList 获取卡列表信息
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *CardListController) GetCardList(ctx *gin.Context) {
	fmt.Printf("[CardListController] ===== 开始处理卡列表查询 =====\n")

	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		fmt.Printf("[CardListController] 错误：未找到平台信息\n")
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	fmt.Printf("[CardListController] 中间件获取到平台信息: PlatformType=%s, MatrixAccount=%s, Status=%s\n",
		platformInfo.PlatformType, platformInfo.MatrixAccount, platformInfo.Status)

	// 直接从数据库验证用户的平台类型
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID > 0 {
		var matrixAccount models.UserMatrixAccount
		if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&matrixAccount).Error; err == nil {
			fmt.Printf("[CardListController] 数据库中的平台类型: %s\n", matrixAccount.PlatformType)
			// 如果数据库中的平台类型与中间件获取的不一致，使用数据库中的
			if matrixAccount.PlatformType != platformInfo.PlatformType {
				fmt.Printf("[CardListController] 平台类型不一致，使用数据库中的类型: %s\n", matrixAccount.PlatformType)
				platformInfo.PlatformType = matrixAccount.PlatformType
			}
		} else {
			fmt.Printf("[CardListController] 数据库查询失败: %v\n", err)
		}
	}

	fmt.Printf("[CardListController] 最终使用的平台类型: %s\n", platformInfo.PlatformType)

	// 根据平台类型选择对应的处理逻辑
	switch platformInfo.PlatformType {
	case "photonpay":
		fmt.Printf("[CardListController] 选择PhotonPay处理逻辑\n")
		c.getPhotonPayCardListAsPhotonPay(ctx)
	case "hlpay":
		fmt.Printf("[CardListController] 选择HlPay处理逻辑\n")
		c.getHlPayCardListAsPhotonPay(ctx)
	default:
		fmt.Printf("[CardListController] 不支持的平台类型: %s\n", platformInfo.PlatformType)
		common.Error(ctx, http.StatusBadRequest, "unsupported_platform_type", nil)
	}

	fmt.Printf("[CardListController] ===== 卡列表查询处理完成 =====\n")
}

// getPhotonPayCardListAsPhotonPay 获取PhotonPay卡列表，返回PhotonPay原始格式
func (c *CardListController) getPhotonPayCardListAsPhotonPay(ctx *gin.Context) {
	// 添加超时控制，增加超时时间
	reqCtx, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
	defer cancel()

	// 获取当前用户ID
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID == 0 {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", fmt.Errorf("user ID not found"))
		return
	}

	// 获取矩阵账户信息 - 从matrix_account_info上下文获取
	matrixInfo, exists := ctx.Get("matrix_account_info")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "matrix_account_not_found", nil)
		return
	}

	matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "matrix_account_invalid", nil)
		return
	}

	// 使用读锁进行用户卡查询，添加错误处理和降级逻辑
	c.mu.RLock()
	var userCards []models.UserCard
	err := c.db.Where("user_id = ? AND platform = ?", userID, "photonpay").Find(&userCards).Error
	c.mu.RUnlock()

	if err != nil {
		fmt.Printf("[CardListController] 查询用户卡失败: %v\n", err)
		// 降级处理：不直接返回错误，而是继续执行，但记录警告
		fmt.Printf("[CardListController] 警告：用户卡查询失败，将尝试从API获取所有数据\n")
		userCards = []models.UserCard{} // 设置为空切片
	}

	// 如果用户没有卡，返回空结果（但允许继续执行以获取可能的卡数据）
	if len(userCards) == 0 {
		fmt.Printf("[CardListController] 用户没有在数据库中注册的卡\n")
		// 不直接返回，而是继续执行API调用
	}

	// 获取分页参数
	page, pageSize := common.GetPaginationParams(ctx)

	// 获取过滤参数
	nickname := ctx.Query("nickname")
	maskCardNo := ctx.Query("cardNo")

	// 获取统一状态参数并映射为平台状态
	unifiedStatus := ctx.Query("cardStatus")
	platformStatus := c.mapUnifiedStatusToPlatformStatus("photonpay", unifiedStatus)

	// 获取模糊查询参数
	nickname = ctx.Query("nickname")
	maskCardNo = ctx.Query("cardNo")

	// 构建查询参数 - 获取所有卡数据，然后在内存中过滤
	params := photonmodels.CardListQueryParams{
		PageIndex:      1,    // 获取第一页，pageSize设置大一些
		PageSize:       1000, // 获取足够多的数据
		MatrixAccount:  matrixAccountInfo.MatrixAccount,
		CardBin:        ctx.Query("cardBin"),
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
		CardType:       ctx.Query("cardType"),
		CardFormFactor: ctx.Query("cardFormFactor"),
		CardStatus:     platformStatus,
	}

	// 添加调试日志
	fmt.Printf("[CardListController] PhotonPay查询参数: %+v\n", params)
	fmt.Printf("[CardListController] 矩阵账户信息: MatrixAccount=%s, UserID=%d\n",
		matrixAccountInfo.MatrixAccount, matrixAccountInfo.UserID)

	// 创建带有用户ID的上下文
	serviceCtx := context.WithValue(reqCtx, "userID", userID)

	// 调用PhotonPay服务，增加超时时间和错误处理
	response, err := photonpayServices.GetCardList(serviceCtx, c.photonpayClient, params)
	if err != nil {
		fmt.Printf("[CardListController] PhotonPay API调用失败: %v\n", err)
		// 如果API调用失败，返回空结果而不是错误
		common.Success(ctx, gin.H{
			"platform": "photonpay",
			"data": gin.H{
				"code":      "0000",
				"msg":       "success",
				"data":      []interface{}{},
				"pageIndex": int64(page),
				"pageSize":  int64(pageSize),
				"total":     0,
			},
		})
		return
	}

	// 创建用户卡ID的映射，用于快速查找
	userCardIDMap := make(map[string]models.UserCard)
	for _, userCard := range userCards {
		userCardIDMap[userCard.CardID] = userCard
	}

	// 过滤出用户有权限的卡，添加降级逻辑
	var authorizedCards []photonmodels.CardInfo
	var totalBalance float64        // 计算总余额
	var totalTransferAmount float64 // 计算总转账金额
	if response.Data != nil {
		fmt.Printf("[CardListController] API返回卡数量: %d, 用户数据库卡数量: %d\n", len(response.Data), len(userCards))

		for _, card := range response.Data {
			// 检查卡是否属于当前用户
			if userCard, exists := userCardIDMap[card.CardID]; exists {
				// 合并用户数据库中的信息
				card.Nickname = userCard.NikeName
				card.TotalTransferAmount = userCard.TotalTransferAmount.InexactFloat64()

				// 转换卡状态为统一状态
				card.CardStatus = common.MapPlatformStatusToUnified("photonpay", card.CardStatus)

				// 计算总余额和总转账金额（只对属于当前用户的卡进行累加）
				totalBalance += card.CardBalance
				totalTransferAmount += card.TotalTransferAmount
			} else {
				// 如果数据库中没有这张卡，但有API数据，可以选择是否包含
				// 这里选择包含，但记录日志
				fmt.Printf("[CardListController] 安全过滤：卡 %s 在API中存在但数据库中未找到，已排除\n", card.CardID)

				// 转换卡状态为统一状态
				card.CardStatus = common.MapPlatformStatusToUnified("photonpay", card.CardStatus)

				// 不属于当前用户的卡不计算余额和转账金额
			}

			// 新增：nickname模糊过滤
			if nickname != "" && !strings.Contains(strings.ToLower(card.Nickname), strings.ToLower(nickname)) {
				continue
			}
			// 新增：maskCardNo模糊过滤
			if maskCardNo != "" && !strings.Contains(card.MaskCardNo, maskCardNo) {
				continue
			}

			authorizedCards = append(authorizedCards, card)
		}
	}

	fmt.Printf("[CardListController] 最终授权卡数量: %d, 总余额: %.2f, 总转账金额: %.2f\n", len(authorizedCards), totalBalance, totalTransferAmount)

	// 应用分页
	total := len(authorizedCards)
	startIndex := int((page - 1) * pageSize)
	endIndex := startIndex + int(pageSize)

	if startIndex >= total {
		// 请求的页码超出范围，返回空结果
		totalPages := (int(total) + int(pageSize) - 1) / int(pageSize)
		common.Success(ctx, gin.H{
			"platform":    "photonpay",
			"data":        []interface{}{},
			"page":        page,
			"page_size":   pageSize,
			"total":       total,
			"total_pages": totalPages,
		})
		return
	}

	if endIndex > total {
		endIndex = total
	}

	// 截取分页数据
	pagedCards := authorizedCards[startIndex:endIndex]

	// 计算总页数
	totalPages := (int(total) + int(pageSize) - 1) / int(pageSize)

	// 构建响应
	responseData := gin.H{
		"platform":    "photonpay",
		"data":        pagedCards,
		"page":        page,
		"page_size":   pageSize,
		"total":       total,
		"total_pages": totalPages,
	}

	// 获取简化的统计信息，传递计算出的总余额
	platformInfo := &middleware.PlatformInfo{
		PlatformType:  "photonpay",
		MatrixAccount: matrixAccountInfo.MatrixAccount,
		Status:        "active",
	}

	// 获取用户角色信息
	var roleID int64 = 2 // 默认普通用户角色
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			roleID = authClaims.RoleID
		}
	}

	var stats *service.SimplifiedCardStatistics
	// 使用新的方法，传递计算出的总余额和总转账金额，以及用户ID和角色ID
	stats, err = c.statisticsService.GetSimplifiedCardStatisticsWithBalance(reqCtx, platformInfo, totalBalance, totalTransferAmount, userID, roleID)
	if err != nil {
		// 如果获取统计信息失败，记录错误但不影响卡列表返回
		fmt.Printf("[CardListController] 获取简化统计信息失败: %v\n", err)
		stats = nil
	}

	// 返回PhotonPay的原始响应格式，包含简化的统计信息
	finalResponse := gin.H{
		"platform": "photonpay",
		"data":     responseData,
	}

	if stats != nil {
		finalResponse["statistics"] = stats
	}

	common.Success(ctx, finalResponse)
}

// getHlPayCardListAsPhotonPay 获取HlPay卡列表，但返回PhotonPay格式
func (c *CardListController) getHlPayCardListAsPhotonPay(ctx *gin.Context) {
	// 添加超时控制，增加超时时间
	reqCtx, cancel := context.WithTimeout(ctx.Request.Context(), 60*time.Second)
	defer cancel()

	// 获取当前用户ID
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID == 0 {
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", fmt.Errorf("user ID not found"))
		return
	}

	// 使用读锁进行用户卡查询，添加错误处理和降级逻辑
	c.mu.RLock()
	var userCards []models.UserCard
	err := c.db.Where("user_id = ? AND platform = ?", userID, "hlPay").Find(&userCards).Error
	c.mu.RUnlock()

	if err != nil {
		fmt.Printf("[CardListController] 查询用户卡失败: %v\n", err)
		// 降级处理：不直接返回错误，而是继续执行，但记录警告
		fmt.Printf("[CardListController] 警告：用户卡查询失败，将尝试从API获取所有数据\n")
		userCards = []models.UserCard{} // 设置为空切片
	}

	// 如果用户没有卡，记录但不直接返回
	if len(userCards) == 0 {
		fmt.Printf("[CardListController] 用户没有在数据库中注册的卡\n")
		// 不直接返回，而是继续执行API调用
	}

	// 获取用户的matrixAccount
	var matrixAccount string
	var userMatrixAccount models.UserMatrixAccount
	if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount).Error; err == nil {
		matrixAccount = userMatrixAccount.MatrixAccount
		fmt.Printf("[CardListController] 获取到用户matrixAccount: %s\n", matrixAccount)
	} else {
		fmt.Printf("[CardListController] 获取用户matrixAccount失败: %v\n", err)
		// 如果获取失败，使用空字符串
		matrixAccount = ""
	}

	// 获取分页参数
	page, pageSize := common.GetPaginationParams(ctx)

	// 获取过滤参数
	cardNo := ctx.Query("cardNo")
	name := ctx.Query("name")
	nickname := ctx.Query("nickname")        // 新增昵称查询
	cardBin := ctx.Query("cardBin")          // 新增卡BIN查询
	maskCardNo := ctx.Query("cardNo")        // 新增卡号查询
	unifiedStatus := ctx.Query("cardStatus") // 使用统一的参数名

	// 如果前端传入的是统一状态，需要映射为平台状态
	platformStatus := c.mapUnifiedStatusToPlatformStatus("hlpay", unifiedStatus)

	// 构建查询参数 - 获取所有卡数据，然后在内存中过滤
	params := &hlpaymodels.CardListRequest{
		CardNo: cardNo,
		Name:   name,
		Status: platformStatus,
	}

	// 调用HlPay服务获取所有卡数据，增加错误处理
	result, err := hlservices.GetCardList(reqCtx, c.hlpayClient, 1, 1000, params)
	if err != nil {
		fmt.Printf("[CardListController] HlPay API调用失败: %v\n", err)
		// 如果API调用失败，返回空结果而不是错误
		common.Success(ctx, gin.H{
			"platform": "hlpay",
			"data": gin.H{
				"code":      "0000",
				"msg":       "success",
				"data":      []interface{}{},
				"pageIndex": int64(page),
				"pageSize":  int64(pageSize),
				"total":     0,
			},
		})
		return
	}

	// 创建用户卡ID的映射，用于快速查找
	userCardIDMap := make(map[string]models.UserCard)
	for _, userCard := range userCards {
		userCardIDMap[userCard.CardID] = userCard
	}

	// 过滤出用户有权限的卡，并合并用户数据库中的信息，同时应用内存过滤条件
	var authorizedRows []hlpaymodels.CardItem
	var totalBalance float64 // 计算总余额
	if result.Rows != nil {
		for _, card := range result.Rows {
			// 检查卡是否属于当前用户
			if userCard, exists := userCardIDMap[card.ID]; exists {
				// 合并用户数据库中的信息
				card.Nickname = userCard.NikeName
				card.TotalTransferAmount = userCard.TotalTransferAmount.String()
				// 只对属于当前用户的卡累加余额
				balance, _ := strconv.ParseFloat(card.ActualBalance, 64)
				totalBalance += balance
				// 应用内存过滤条件
				// 1. 昵称过滤
				if nickname != "" && !strings.Contains(strings.ToLower(card.Nickname), strings.ToLower(nickname)) {
					continue
				}
				// 2. 卡BIN过滤（从卡号前6位提取）
				if cardBin != "" {
					cardBinFromCard := ""
					if len(card.CardNo) >= 6 {
						cardBinFromCard = card.CardNo[:6]
					}
					if !strings.Contains(strings.ToLower(cardBinFromCard), strings.ToLower(cardBin)) {
						continue
					}
				}
				// 3. 掩码卡号过滤
				if maskCardNo != "" {
					// 动态生成掩码卡号
					maskCardNoLocal := ""
					if len(card.CardNo) > 8 {
						maskCardNoLocal = card.CardNo[:4] + "****" + card.CardNo[len(card.CardNo)-4:]
					} else {
						maskCardNoLocal = card.CardNo
					}
					if !strings.Contains(maskCardNoLocal, maskCardNo) {
						continue
					}
				}

				authorizedRows = append(authorizedRows, card)
			}
		}
	}

	// 应用分页
	total := len(authorizedRows)
	startIndex := int((page - 1) * pageSize)
	endIndex := startIndex + int(pageSize)

	if startIndex >= total {
		// 请求的页码超出范围，返回空结果
		totalPages := (int(total) + int(pageSize) - 1) / int(pageSize)
		common.Success(ctx, gin.H{
			"platform":    "hlpay",
			"data":        []interface{}{},
			"page":        page,
			"page_size":   pageSize,
			"total":       total,
			"total_pages": totalPages,
		})
		return
	}

	if endIndex > total {
		endIndex = total
	}

	// 截取分页数据
	pagedCards := authorizedRows[startIndex:endIndex]

	// 构建HlPay响应格式
	hlpayResponse := &hlpaymodels.CardListResponse{
		Total:   total,
		Rows:    pagedCards,
		Code:    result.Code,
		Message: result.Message,
	}

	// 转换为PhotonPay格式，传递matrixAccount
	photonpayResponse := c.convertHlPayToPhotonPayFormat(hlpayResponse, userID, matrixAccount)

	// 获取用户角色信息
	var roleID int64 = 2 // 默认普通用户角色
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			roleID = authClaims.RoleID
		}
	}

	// 获取简化的统计信息 - 基于用户实际有权限的卡数据
	var stats *service.SimplifiedCardStatistics
	stats, err = c.calculateHlPayStatisticsFromAuthorizedCards(authorizedRows, totalBalance, userID, roleID)
	if err != nil {
		// 如果获取简化统计信息失败，记录错误但不影响卡列表返回
		fmt.Printf("[CardListController] 获取HlPay简化统计信息失败: %v\n", err)
		stats = nil
	}

	// 返回PhotonPay格式的响应，包含简化的统计信息
	responseData := gin.H{
		"platform": "hlpay",
		"data":     photonpayResponse,
	}

	if stats != nil {
		responseData["statistics"] = stats
	}

	common.Success(ctx, responseData)
}

// convertHlPayToPhotonPayFormat 将HlPay响应转换为PhotonPay格式
func (c *CardListController) convertHlPayToPhotonPayFormat(hlpayResponse *hlpaymodels.CardListResponse, userID int64, matrixAccount string) *photonmodels.CardListResponse {
	// 创建PhotonPay格式的响应
	photonpayResponse := &photonmodels.CardListResponse{
		BaseResponse: photonmodels.BaseResponse{
			Code: "0000",
			Msg:  json.RawMessage(`"success"`),
		},
		PageIndex: 1,
		PageSize:  int64(len(hlpayResponse.Rows)),
		Total:     int64(hlpayResponse.Total),
		Data:      make([]photonmodels.CardInfo, 0, len(hlpayResponse.Rows)),
	}

	// 转换每个卡片信息（此时传入的数据已经是经过权限过滤的）
	for _, card := range hlpayResponse.Rows {
		// 解析余额
		balance, _ := strconv.ParseFloat(card.ActualBalance, 64)

		// 解析总转账金额
		transferAmount := 0.0
		if card.TotalTransferAmount != "" {
			transferAmount, _ = strconv.ParseFloat(card.TotalTransferAmount, 64)
		}

		// 获取卡BIN（从卡号前6位）
		cardBin := ""
		if len(card.CardNo) >= 6 {
			cardBin = card.CardNo[:6]
		}

		// 获取卡Scheme（根据BIN判断）
		cardScheme := ""
		if strings.HasPrefix(cardBin, "4") {
			cardScheme = "VISA"
		} else if strings.HasPrefix(cardBin, "5") {
			cardScheme = "MASTERCARD"
		}

		// 转换卡状态格式 - 使用统一状态映射，返回统一状态给前端
		cardStatus := common.MapPlatformStatusToUnified("hlpay", card.Status)

		photonpayCard := photonmodels.CardInfo{
			CardBalance:         balance,
			CardCurrency:        "USD", // HlPay默认USD
			CardID:              card.ID,
			CardScheme:          cardScheme,
			CardStatus:          cardStatus,
			CardType:            "recharge", // HlPay默认常规卡
			CreatedAt:           card.CreateTime,
			MatrixAccount:       matrixAccount,
			MemberID:            "", // HlPay没有会员ID概念
			MaskCardNo:          c.maskCardNo(card.CardNo),
			Nickname:            card.Nickname,
			CardFormFactor:      "virtual_card", // HlPay默认虚拟卡
			TotalTransferAmount: transferAmount,
			TransactionLimit:    nil, // HlPay没有交易限额字段
		}

		photonpayResponse.Data = append(photonpayResponse.Data, photonpayCard)
	}

	return photonpayResponse
}

// handlePhotonPayCardList 处理PhotonPay平台的卡列表查询
func (c *CardListController) handlePhotonPayCardList(ctx *gin.Context) {
	// 获取矩阵账户信息 - 从matrix_account_info上下文获取
	matrixInfo, exists := ctx.Get("matrix_account_info")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "matrix_account_not_found", nil)
		return
	}

	matrixAccountInfo, ok := matrixInfo.(*models.UserMatrixAccount)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "matrix_account_invalid", nil)
		return
	}

	// 获取用户角色
	claims, exists := ctx.Get("claims")
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "unauthorized", nil)
		return
	}
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		common.Error(ctx, http.StatusInternalServerError, "invalid_token_claims", nil)
		return
	}
	roleID := authClaims.RoleID
	userID := authClaims.UserID

	// 获取分页参数
	page, pageSize := common.GetPaginationParams(ctx)

	// 获取过滤参数
	nickname := ctx.Query("nickname")
	maskCardNo := ctx.Query("cardNo")
	cardType := ctx.Query("cardType")

	// 获取统一状态参数并映射为平台状态
	unifiedStatus := ctx.Query("cardStatus")
	platformStatus := c.mapUnifiedStatusToPlatformStatus("photonpay", unifiedStatus)

	// 构建查询参数 - 使用实际的分页参数
	params := photonmodels.CardListQueryParams{
		PageIndex:      int(page),
		PageSize:       int(pageSize),
		MatrixAccount:  matrixAccountInfo.MatrixAccount,
		CardBin:        ctx.Query("cardBin"),
		CreatedAtStart: ctx.Query("createdAtStart"),
		CreatedAtEnd:   ctx.Query("createdAtEnd"),
		CardType:       cardType,
		CardFormFactor: ctx.Query("cardFormFactor"),
		CardStatus:     platformStatus,
	}

	// 添加调试日志
	fmt.Printf("[CardListController] PhotonPay查询参数: %+v\n", params)
	fmt.Printf("[CardListController] 矩阵账户信息: MatrixAccount=%s, UserID=%d\n",
		matrixAccountInfo.MatrixAccount, matrixAccountInfo.UserID)

	// 创建带有用户ID的上下文
	serviceCtx := context.WithValue(ctx.Request.Context(), "userID", userID)

	// 调用PhotonPay服务
	response, err := photonpayServices.GetCardList(serviceCtx, c.photonpayClient, params)
	if err != nil {
		fmt.Printf("[CardListController] PhotonPay服务调用失败: %v\n", err)
		common.Error(ctx, http.StatusInternalServerError, "photonpay_get_card_list_failed", err)
		return
	}

	// 转换卡状态为统一状态
	if response.Data != nil {
		for i := range response.Data {
			// 将平台状态转换为统一状态
			response.Data[i].CardStatus = common.MapPlatformStatusToUnified("photonpay", response.Data[i].CardStatus)
		}
	}

	fmt.Printf("[CardListController] PhotonPay响应: code=%s, total=%d, data_len=%d\n",
		response.Code, response.Total, len(response.Data))

	// 检查响应是否为空
	if response.Data == nil {
		fmt.Printf("[CardListController] PhotonPay响应数据为空\n")
		// 返回空响应
		common.Success(ctx, gin.H{
			"platform": "photonpay",
			"data": gin.H{
				"code":      "0000",
				"msg":       "success",
				"data":      []interface{}{},
				"pageIndex": int64(page),
				"pageSize":  int64(pageSize),
				"total":     0,
			},
		})
		return
	}

	// 在内存中进行过滤（如果需要额外的过滤）
	filteredCards := make([]photonmodels.CardInfo, 0)
	for i := range response.Data {
		card := &response.Data[i]

		// 只有子账号用户需要过滤自己的卡
		if roleID == 5 {
			var userCard models.UserCard
			if err := c.db.Where("card_id = ? AND user_id = ?", card.CardID, userID).First(&userCard).Error; err != nil {
				continue // 如果查询失败或卡不属于该用户，跳过
			}
		}

		// 从数据库获取用户设置的昵称
		var userCard models.UserCard
		if err := c.db.Where("card_id = ? AND user_id = ?", card.CardID, userID).First(&userCard).Error; err == nil {
			// 如果数据库中有昵称，使用数据库中的昵称
			if userCard.NikeName != "" {
				card.Nickname = userCard.NikeName
			}
		}

		// 检查 nickname 匹配（使用数据库中的昵称）
		if nickname != "" {
			cardNickname := card.Nickname
			if userCard.NikeName != "" {
				cardNickname = userCard.NikeName
			}
			if !strings.Contains(strings.ToLower(cardNickname), strings.ToLower(nickname)) {
				continue
			}
		}

		// 检查 maskCardNo 匹配（直接用 card.MaskCardNo）
		if maskCardNo != "" && !strings.Contains(card.MaskCardNo, maskCardNo) {
			continue
		}

		// 如果是共享卡，设置交易限额
		if cardType == "share" {
			if err := c.db.Where("card_id = ?", card.CardID).First(&userCard).Error; err == nil {
				limit := userCard.TotalTransferAmount.InexactFloat64()
				card.TransactionLimit = &limit
			}
		}

		filteredCards = append(filteredCards, *card)
	}

	fmt.Printf("[CardListController] 过滤后卡片数量: %d\n", len(filteredCards))

	// 如果进行了内存过滤，更新响应数据
	if len(filteredCards) != len(response.Data) {
		response.Data = filteredCards
		response.Total = int64(len(filteredCards))
	}

	// 返回成功响应
	common.Success(ctx, gin.H{
		"platform": "photonpay",
		"data":     response,
	})
}

// handleHlPayCardList 处理HlPay平台的卡列表查询
func (c *CardListController) handleHlPayCardList(ctx *gin.Context) {
	// 添加超时控制
	reqCtx, cancel := context.WithTimeout(ctx.Request.Context(), 30*time.Second)
	defer cancel()

	fmt.Printf("[CardListController] 开始处理HlPay卡列表查询\n")

	// 获取当前用户ID
	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}

	if userID == 0 {
		fmt.Printf("[CardListController] 错误：未找到用户ID\n")
		common.Error(ctx, http.StatusUnauthorized, "user_not_found", fmt.Errorf("user ID not found"))
		return
	}

	fmt.Printf("[CardListController] 用户ID: %d\n", userID)

	// 获取用户的matrixAccount
	var matrixAccount string
	var userMatrixAccount models.UserMatrixAccount
	if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount).Error; err == nil {
		matrixAccount = userMatrixAccount.MatrixAccount
		fmt.Printf("[CardListController] 获取到用户matrixAccount: %s\n", matrixAccount)
	} else {
		fmt.Printf("[CardListController] 获取用户matrixAccount失败: %v\n", err)
		// 如果获取失败，使用空字符串
		matrixAccount = ""
	}

	// 获取分页参数
	page, pageSize := common.GetPaginationParams(ctx)
	fmt.Printf("[CardListController] 分页参数: page=%d, pageSize=%d\n", page, pageSize)

	// 获取过滤参数
	cardNo := ctx.Query("cardNo")
	name := ctx.Query("name")
	nickname := ctx.Query("nickname")        // 新增昵称查询
	cardBin := ctx.Query("cardBin")          // 新增卡BIN查询
	maskCardNo := ctx.Query("cardNo")        // 新增卡号查询
	unifiedStatus := ctx.Query("cardStatus") // 使用统一的参数名

	// 如果前端传入的是统一状态，需要映射为平台状态
	platformStatus := c.mapUnifiedStatusToPlatformStatus("hlpay", unifiedStatus)
	fmt.Printf("[CardListController] 过滤参数: cardNo=%s, name=%s, nickname=%s, cardBin=%s, unifiedStatus=%s, platformStatus=%s\n",
		cardNo, name, nickname, cardBin, unifiedStatus, platformStatus)

	// 构建查询参数
	params := &hlpaymodels.CardListRequest{
		CardNo: cardNo,
		Name:   name,
		Status: platformStatus,
	}

	// 生成缓存键（包含用户ID，因为不同用户看到的数据不同）
	cacheKey := fmt.Sprintf("hlpay:card_list:user_%d:%s:%s:%s",
		userID,
		func() string {
			if params.CardNo != "" {
				return params.CardNo
			}
			return "all"
		}(),
		func() string {
			if params.Name != "" {
				return params.Name
			}
			return "all"
		}(),
		func() string {
			if params.Status != "" {
				return params.Status
			}
			return "all"
		}())

	// 首先尝试从Redis获取缓存
	cachedData, err := database.Get(reqCtx, cacheKey)
	if err == nil && cachedData != "" {
		// 缓存命中，解析原始数据并重新进行权限过滤和信息合并
		var allResult hlpaymodels.CardListResponse
		if err := json.Unmarshal([]byte(cachedData), &allResult); err == nil {
			// 使用读锁进行用户卡查询
			c.mu.RLock()
			var userCards []models.UserCard
			if err := c.db.Where("user_id = ? AND platform = ?", userID, "hlPay").Find(&userCards).Error; err != nil {
				c.mu.RUnlock()
				fmt.Printf("[CardListController] 查询用户卡失败: %v\n", err)
				common.Error(ctx, http.StatusInternalServerError, "get_user_cards_failed", err)
				return
			}
			c.mu.RUnlock()

			fmt.Printf("[CardListController] 查询到用户卡数量: %d\n", len(userCards))

			// 获取用户角色信息
			var roleID int64
			if claims, exists := ctx.Get("claims"); exists {
				if authClaims, ok := claims.(*auth.Claims); ok {
					roleID = authClaims.RoleID
				}
			}

			fmt.Printf("[CardListController] 用户角色ID: %d\n", roleID)

			// 创建用户卡ID的映射，用于快速查找，同时保存用户卡信息
			userCardIDMap := make(map[string]bool)
			userCardInfoMap := make(map[string]models.UserCard)
			for _, userCard := range userCards {
				userCardIDMap[userCard.CardID] = true
				userCardInfoMap[userCard.CardID] = userCard
			}

			fmt.Printf("[CardListController] 用户卡ID映射: %v\n", userCardIDMap)

			// 过滤出用户有权限的卡，并合并用户数据库中的信息
			var authorizedRows []hlpaymodels.CardItem
			for _, card := range allResult.Rows {
				// 只显示用户有权限的卡（从user_cards表中查询到的卡）
				if userCardIDMap[card.ID] {
					// 如果用户数据库中有这张卡的信息，合并信息
					if userCard, exists := userCardInfoMap[card.ID]; exists {
						card.Nickname = userCard.NikeName
						card.TotalTransferAmount = userCard.TotalTransferAmount.String()
					}

					authorizedRows = append(authorizedRows, card)
				}
			}

			fmt.Printf("[CardListController] 过滤后用户有权限的卡数量: %d (总卡数: %d)\n", len(authorizedRows), len(allResult.Rows))

			// 从过滤后的数据中截取对应的分页数据
			startIndex := int((page - 1) * pageSize)
			endIndex := startIndex + int(pageSize)

			if startIndex >= len(authorizedRows) {
				// 请求的页码超出范围，返回空结果
				result := hlpaymodels.CardListResponse{
					Total:   int(len(authorizedRows)),
					Rows:    []hlpaymodels.CardItem{},
					Code:    allResult.Code,
					Message: allResult.Message,
				}
				standardizedResponse := c.convertHlPayCardListToStandard(&result, matrixAccount)

				// 获取简化的统计信息 - 基于用户实际有权限的卡数据
				var totalBalanceCache float64
				for _, card := range authorizedRows {
					balance, _ := strconv.ParseFloat(card.ActualBalance, 64)
					totalBalanceCache += balance
				}
				// 获取用户角色信息
				var roleID int64 = 2 // 默认普通用户角色
				if claims, exists := ctx.Get("claims"); exists {
					if authClaims, ok := claims.(*auth.Claims); ok {
						roleID = authClaims.RoleID
					}
				}

				var stats *service.SimplifiedCardStatistics
				stats, err = c.calculateHlPayStatisticsFromAuthorizedCards(authorizedRows, totalBalanceCache, userID, roleID)
				if err != nil {
					// 如果获取简化统计信息失败，记录错误但不影响卡列表返回
					fmt.Printf("[CardListController] 获取HlPay简化统计信息失败: %v\n", err)
					stats = nil
				}

				responseData := gin.H{
					"platform": "hlpay",
					"data":     standardizedResponse,
				}

				if stats != nil {
					responseData["statistics"] = stats
				}

				common.Success(ctx, responseData)
				return
			}

			if endIndex > len(authorizedRows) {
				endIndex = len(authorizedRows)
			}

			result := hlpaymodels.CardListResponse{
				Total:   int(len(authorizedRows)),
				Rows:    authorizedRows[startIndex:endIndex],
				Code:    allResult.Code,
				Message: allResult.Message,
			}
			standardizedResponse := c.convertHlPayCardListToStandard(&result, matrixAccount)

			// 获取简化的统计信息 - 基于用户实际有权限的卡数据
			var totalBalanceCache2 float64
			for _, card := range authorizedRows {
				balance, _ := strconv.ParseFloat(card.ActualBalance, 64)
				totalBalanceCache2 += balance
			}
			// 获取用户角色信息
			var roleID2 int64 = 2 // 默认普通用户角色
			if claims, exists := ctx.Get("claims"); exists {
				if authClaims, ok := claims.(*auth.Claims); ok {
					roleID2 = authClaims.RoleID
				}
			}

			var stats2 *service.SimplifiedCardStatistics
			stats2, err = c.calculateHlPayStatisticsFromAuthorizedCards(authorizedRows, totalBalanceCache2, userID, roleID2)
			if err != nil {
				// 如果获取简化统计信息失败，记录错误但不影响卡列表返回
				fmt.Printf("[CardListController] 获取HlPay简化统计信息失败: %v\n", err)
				stats2 = nil
			}

			responseData := gin.H{
				"platform": "hlpay",
				"data":     standardizedResponse,
			}

			if stats2 != nil {
				responseData["statistics"] = stats2
			}

			common.Success(ctx, responseData)
			return
		}
	}

	// 缓存未命中，获取所有数据
	// 先获取第一页，pageSize=1000
	fmt.Printf("[CardListController] 开始调用HlPay API获取卡列表\n")
	firstPageResult, err := hlservices.GetCardList(reqCtx, c.hlpayClient, 1, 1000, params)
	if err != nil {
		fmt.Printf("[CardListController] HlPay API调用失败: %v\n", err)
		common.Error(ctx, http.StatusInternalServerError, "hlpay_get_card_list_failed", err)
		return
	}

	if firstPageResult == nil {
		fmt.Printf("[CardListController] HlPay API返回空结果\n")
		common.Error(ctx, http.StatusInternalServerError, "hlpay_get_card_list_failed", fmt.Errorf("first page result is nil"))
		return
	}

	fmt.Printf("[CardListController] HlPay API调用成功: total=%d, rows=%d\n", firstPageResult.Total, len(firstPageResult.Rows))

	// 合并所有数据
	allRows := firstPageResult.Rows
	total := firstPageResult.Total

	// 计算还需要获取多少页
	totalPages := (int(total) + int(pageSize) - 1) / int(pageSize)

	// 获取剩余页的数据
	for currentPage := 2; currentPage <= totalPages; currentPage++ {
		pageResult, err := hlservices.GetCardList(reqCtx, c.hlpayClient, currentPage, 1000, params)
		if err != nil {
			continue
		}

		if pageResult != nil && len(pageResult.Rows) > 0 {
			allRows = append(allRows, pageResult.Rows...)
		}
	}

	// 使用读锁进行用户卡查询
	c.mu.RLock()
	var userCards []models.UserCard
	if err := c.db.Where("user_id = ? AND platform = ?", userID, "hlPay").Find(&userCards).Error; err != nil {
		c.mu.RUnlock()
		fmt.Printf("[CardListController] 查询用户卡失败: %v\n", err)
		common.Error(ctx, http.StatusInternalServerError, "get_user_cards_failed", err)
		return
	}
	c.mu.RUnlock()

	fmt.Printf("[CardListController] 查询到用户卡数量: %d\n", len(userCards))

	// 获取用户角色信息
	var roleID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			roleID = authClaims.RoleID
		}
	}

	fmt.Printf("[CardListController] 用户角色ID: %d\n", roleID)

	// 创建用户卡ID的映射，用于快速查找，同时保存用户卡信息
	userCardIDMap := make(map[string]bool)
	userCardInfoMap := make(map[string]models.UserCard)
	for _, userCard := range userCards {
		userCardIDMap[userCard.CardID] = true
		userCardInfoMap[userCard.CardID] = userCard
	}

	fmt.Printf("[CardListController] 用户卡ID映射: %v\n", userCardIDMap)

	// 过滤出用户有权限的卡，并合并用户数据库中的信息，同时应用内存过滤条件
	var authorizedRows []hlpaymodels.CardItem
	for _, card := range allRows {
		// 只显示用户有权限的卡（从user_cards表中查询到的卡）
		if userCardIDMap[card.ID] {
			// 如果用户数据库中有这张卡的信息，合并信息
			if userCard, exists := userCardInfoMap[card.ID]; exists {
				card.Nickname = userCard.NikeName
				card.TotalTransferAmount = userCard.TotalTransferAmount.String()
			}

			// 应用内存过滤条件
			// 1. 昵称过滤
			if nickname != "" && !strings.Contains(strings.ToLower(card.Nickname), strings.ToLower(nickname)) {
				continue
			}
			// 2. 卡BIN过滤（从卡号前6位提取）
			if cardBin != "" {
				cardBinFromCard := ""
				if len(card.CardNo) >= 6 {
					cardBinFromCard = card.CardNo[:6]
				}
				if !strings.Contains(strings.ToLower(cardBinFromCard), strings.ToLower(cardBin)) {
					continue
				}
			}
			// 3. 掩码卡号过滤
			if maskCardNo != "" {
				// 动态生成掩码卡号
				maskCardNoLocal := ""
				if len(card.CardNo) > 8 {
					maskCardNoLocal = card.CardNo[:4] + "****" + card.CardNo[len(card.CardNo)-4:]
				} else {
					maskCardNoLocal = card.CardNo
				}
				if !strings.Contains(maskCardNoLocal, maskCardNo) {
					continue
				}
			}

			authorizedRows = append(authorizedRows, card)
		}
	}

	fmt.Printf("[CardListController] 过滤后用户有权限的卡数量: %d (总卡数: %d)\n", len(authorizedRows), len(allRows))

	// 构建完整的结果（存储原始数据，不包含用户权限过滤）
	allResult := hlpaymodels.CardListResponse{
		Total:   total,   // 使用原始的总数
		Rows:    allRows, // 使用原始的所有数据
		Code:    firstPageResult.Code,
		Message: firstPageResult.Message,
	}

	// 将原始结果缓存到Redis，过期时间60秒
	if resultBytes, err := json.Marshal(allResult); err == nil {
		database.SetWithExpiration(reqCtx, cacheKey, string(resultBytes), 60*time.Second)
	}

	// 返回请求的分页数据
	startIndex := int((page - 1) * pageSize)
	endIndex := startIndex + int(pageSize)

	if startIndex >= len(authorizedRows) {
		// 请求的页码超出范围，返回空结果
		result := hlpaymodels.CardListResponse{
			Total:   int(len(authorizedRows)),
			Rows:    []hlpaymodels.CardItem{},
			Code:    firstPageResult.Code,
			Message: firstPageResult.Message,
		}
		standardizedResponse := c.convertHlPayCardListToStandard(&result, matrixAccount)
		common.Success(ctx, gin.H{
			"platform": "hlpay",
			"data":     standardizedResponse,
		})
		return
	}

	if endIndex > len(authorizedRows) {
		endIndex = len(authorizedRows)
	}

	result := hlpaymodels.CardListResponse{
		Total:   int(len(authorizedRows)),
		Rows:    authorizedRows[startIndex:endIndex],
		Code:    firstPageResult.Code,
		Message: firstPageResult.Message,
	}

	// 转换为统一格式
	standardizedResponse := c.convertHlPayCardListToStandard(&result, matrixAccount)

	// 获取简化的统计信息 - 基于用户实际有权限的卡数据
	var totalBalanceCache3 float64
	for _, card := range authorizedRows {
		balance, _ := strconv.ParseFloat(card.ActualBalance, 64)
		totalBalanceCache3 += balance
	}
	// 获取用户角色信息
	var roleID3 int64 = 2 // 默认普通用户角色
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			roleID3 = authClaims.RoleID
		}
	}

	var stats3 *service.SimplifiedCardStatistics
	stats3, err = c.calculateHlPayStatisticsFromAuthorizedCards(authorizedRows, totalBalanceCache3, userID, roleID3)
	if err != nil {
		// 如果获取简化统计信息失败，记录错误但不影响卡列表返回
		fmt.Printf("[CardListController] 获取HlPay简化统计信息失败: %v\n", err)
		stats3 = nil
	}

	// 返回成功响应
	responseData := gin.H{
		"platform": "hlpay",
		"data":     standardizedResponse,
	}

	if stats3 != nil {
		responseData["statistics"] = stats3
	}

	common.Success(ctx, responseData)
}

// convertHlPayCardListToStandard 将HlPay卡列表转换为标准格式
func (c *CardListController) convertHlPayCardListToStandard(hlpayResponse *hlpaymodels.CardListResponse, matrixAccount string) gin.H {
	// 转换为PhotonPay格式的响应结构
	standardResponse := gin.H{
		"code":      "0000",
		"msg":       "success",
		"data":      make([]gin.H, 0, len(hlpayResponse.Rows)),
		"pageIndex": 1,
		"pageSize":  int64(len(hlpayResponse.Rows)),
		"total":     int64(hlpayResponse.Total),
	}

	// 转换每个卡片信息
	for _, card := range hlpayResponse.Rows {
		// 解析余额
		balance, _ := strconv.ParseFloat(card.ActualBalance, 64)

		// 解析转账金额 - 此时card.TotalTransferAmount应该已经被设置
		transferAmount := 0.0
		if card.TotalTransferAmount != "" {
			transferAmount, _ = strconv.ParseFloat(card.TotalTransferAmount, 64)
		}

		// 转换卡状态格式 - 使用统一状态映射，返回统一状态给前端
		cardStatus := common.MapPlatformStatusToUnified("hlpay", card.Status)

		// 获取卡BIN（从卡号前6位）
		cardBin := ""
		if len(card.CardNo) >= 6 {
			cardBin = card.CardNo[:6]
		}

		// 获取卡Scheme（根据BIN判断）
		cardScheme := ""
		if strings.HasPrefix(cardBin, "4") {
			cardScheme = "VISA"
		} else if strings.HasPrefix(cardBin, "5") {
			cardScheme = "MASTERCARD"
		}

		standardCard := gin.H{
			"cardBalance":         balance,
			"cardCurrency":        "USD", // HlPay默认USD
			"cardId":              card.ID,
			"cardScheme":          cardScheme,
			"cardStatus":          cardStatus,
			"cardType":            "recharge", // HlPay默认常规卡
			"createdAt":           card.CreateTime,
			"matrixAccount":       matrixAccount, // 使用传入的matrixAccount
			"memberId":            "",            // HlPay没有这个字段，设为空
			"maskCardNo":          c.maskCardNo(card.CardNo),
			"nickname":            card.Nickname,
			"cardFormFactor":      "virtual_card", // HlPay默认虚拟卡
			"totalTransferAmount": transferAmount,
			// 移除HlPay特有字段，保持与PhotonPay一致
		}

		standardResponse["data"] = append(standardResponse["data"].([]gin.H), standardCard)
	}

	return standardResponse
}

// maskCardNo 掩码卡号
func (c *CardListController) maskCardNo(cardNo string) string {
	if len(cardNo) <= 8 {
		return cardNo
	}
	return cardNo[:4] + "****" + cardNo[len(cardNo)-4:]
}

// GetCardListByPlatform 根据指定平台获取卡列表信息
// 允许管理员或高级用户查询指定平台的卡列表信息
func (c *CardListController) GetCardListByPlatform(ctx *gin.Context) {
	// 从URL参数获取平台类型
	platformType := ctx.Param("platform")
	if platformType == "" {
		common.Error(ctx, http.StatusBadRequest, "platform_parameter_required", nil)
		return
	}

	// 验证平台类型是否支持
	switch platformType {
	case "photonpay":
		c.handlePhotonPayCardList(ctx)
	case "hlpay":
		c.handleHlPayCardList(ctx)
	default:
		common.Error(ctx, http.StatusBadRequest, "unsupported_platform_type", nil)
	}
}

// GetCardListComparison 获取两个平台的卡列表对比信息
// 用于比较不同平台的卡列表差异
func (c *CardListController) GetCardListComparison(ctx *gin.Context) {
	// 获取查询参数
	page, pageSize := common.GetPaginationParams(ctx)

	// 并发查询两个平台的卡列表信息
	photonpayChan := make(chan interface{}, 1)
	hlpayChan := make(chan interface{}, 1)
	errorChan := make(chan error, 2)

	// 查询PhotonPay
	go func() {
		matrixAccountInfo, err := common.GetMatrixAccountInfo(ctx)
		if err != nil {
			errorChan <- err
			return
		}

		// 获取统一状态参数并映射为平台状态
		unifiedStatus := ctx.Query("cardStatus")
		platformStatus := c.mapUnifiedStatusToPlatformStatus("photonpay", unifiedStatus)

		params := photonmodels.CardListQueryParams{
			PageIndex:      int(page),
			PageSize:       int(pageSize),
			MatrixAccount:  matrixAccountInfo.MatrixAccount,
			CardBin:        ctx.Query("cardBin"),
			CreatedAtStart: ctx.Query("createdAtStart"),
			CreatedAtEnd:   ctx.Query("createdAtEnd"),
			CardType:       ctx.Query("cardType"),
			CardFormFactor: ctx.Query("cardFormFactor"),
			CardStatus:     platformStatus,
		}

		result, err := photonpayServices.GetCardList(ctx.Request.Context(), c.photonpayClient, params)
		if err != nil {
			errorChan <- err
			return
		}

		// 转换卡状态为统一状态
		if result.Data != nil {
			for i := range result.Data {
				result.Data[i].CardStatus = common.MapPlatformStatusToUnified("photonpay", result.Data[i].CardStatus)
			}
		}

		photonpayChan <- result
	}()

	// 查询HlPay
	go func() {
		// 获取统一状态参数并映射为平台状态
		unifiedStatus := ctx.Query("cardStatus")
		platformStatus := c.mapUnifiedStatusToPlatformStatus("hlpay", unifiedStatus)

		params := &hlpaymodels.CardListRequest{
			CardNo: ctx.Query("cardNo"),
			Name:   ctx.Query("name"),
			Status: platformStatus,
		}
		result, err := hlservices.GetCardList(ctx.Request.Context(), c.hlpayClient, int(page), int(pageSize), params)
		if err != nil {
			errorChan <- err
			return
		}

		// 转换卡状态为统一状态
		if result.Rows != nil {
			for i := range result.Rows {
				result.Rows[i].Status = common.MapPlatformStatusToUnified("hlpay", result.Rows[i].Status)
			}
		}

		hlpayChan <- result
	}()

	// 收集结果
	var photonpayResult interface{}
	var hlpayResult interface{}
	var photonpayError error
	var hlpayError error

	// 等待PhotonPay结果
	select {
	case result := <-photonpayChan:
		photonpayResult = result
	case err := <-errorChan:
		photonpayError = err
	}

	// 等待HlPay结果
	select {
	case result := <-hlpayChan:
		hlpayResult = result
	case err := <-errorChan:
		hlpayError = err
	}

	// 构建对比结果
	comparison := gin.H{
		"photonpay": gin.H{
			"success": photonpayError == nil,
			"data":    photonpayResult,
			"error":   photonpayError,
		},
		"hlpay": gin.H{
			"success": hlpayError == nil,
			"data":    hlpayResult,
			"error":   hlpayError,
		},
	}

	// 如果两个平台都查询失败，返回错误
	if photonpayError != nil && hlpayError != nil {
		common.Error(ctx, http.StatusInternalServerError, "both_platforms_failed", nil)
		return
	}

	common.Success(ctx, comparison)
}

// GetSupportedPlatforms 获取支持的平台列表
func (c *CardListController) GetSupportedPlatforms(ctx *gin.Context) {
	platforms := []gin.H{
		{
			"platform": "photonpay",
			"name":     "光子支付",
			"status":   "active",
		},
		{
			"platform": "hlpay",
			"name":     "HlPay",
			"status":   "active",
		},
	}

	common.Success(ctx, gin.H{
		"platforms": platforms,
	})
}

// mapUnifiedStatusToPlatformStatus 将统一状态映射为平台状态
func (c *CardListController) mapUnifiedStatusToPlatformStatus(platform string, unifiedStatus string) string {
	if platform == "hlpay" {
		switch strings.ToLower(unifiedStatus) {
		case "normal":
			return "Active"
		case "frozen":
			return "Frozen"
		case "cancelled":
			return "Inactive"
		}
	}
	// 其他平台或未匹配，返回原值
	return unifiedStatus
}

// mapPlatformStatusToUnifiedStatus 将平台状态映射为统一状态
func (c *CardListController) mapPlatformStatusToUnifiedStatus(platform string, platformStatus string) string {
	if platformStatus == "" {
		return ""
	}

	// 使用统一状态映射工具
	return common.MapPlatformStatusToUnified(platform, platformStatus)
}

// GetCardStatusOptions 获取支持的卡状态选项
func (c *CardListController) GetCardStatusOptions(ctx *gin.Context) {
	platform := ctx.Query("platform")
	if platform == "" {
		// 如果没有指定平台，返回统一状态
		statusOptions := []gin.H{
			{"value": common.CardStatusNormal, "label": common.GetCardStatusDescription(common.CardStatusNormal)},
			{"value": common.CardStatusUnactivated, "label": common.GetCardStatusDescription(common.CardStatusUnactivated)},
			{"value": common.CardStatusFrozen, "label": common.GetCardStatusDescription(common.CardStatusFrozen)},
			{"value": common.CardStatusCancelled, "label": common.GetCardStatusDescription(common.CardStatusCancelled)},
			{"value": common.CardStatusExpired, "label": common.GetCardStatusDescription(common.CardStatusExpired)},
		}

		common.Success(ctx, gin.H{
			"statusOptions": statusOptions,
			"platform":      "unified",
		})
		return
	}

	// 根据平台返回对应的状态选项
	var statusOptions []gin.H
	switch platform {
	case "photonpay":
		statusOptions = []gin.H{
			{"value": "NORMAL", "label": "可用"},
			{"value": "INACTIVE", "label": "未激活"},
			{"value": "FROZEN", "label": "冻结"},
			{"value": "CANCELLED", "label": "已注销"},
			{"value": "EXPIRED", "label": "过期"},
		}
	case "hlpay":
		statusOptions = []gin.H{
			{"value": "ACTIVE", "label": "活跃"},
			{"value": "INACTIVE", "label": "不活跃"},
			{"value": "FROZEN", "label": "冻结"},
			{"value": "CANCELLED", "label": "已注销"},
			{"value": "CLOSED", "label": "关闭"},
		}
	default:
		common.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	common.Success(ctx, gin.H{
		"statusOptions": statusOptions,
		"platform":      platform,
	})
}

// calculateHlPayStatisticsFromAuthorizedCards 计算HlPay的简化统计信息
func (c *CardListController) calculateHlPayStatisticsFromAuthorizedCards(authorizedCards []hlpaymodels.CardItem, totalBalance float64, userID int64, roleID int64) (*service.SimplifiedCardStatistics, error) {
	stats := &service.SimplifiedCardStatistics{
		TotalCards:   int64(len(authorizedCards)),
		ActiveCards:  0,
		FrozenCards:  0,
		TotalBalance: totalBalance, // 用传入的余额
	}

	// 获取当前用户的账户余额信息
	var userAccountBalance float64
	switch roleID {
	case 3: // 主账号
		var masterAccount models.MasterAccount
		if err := c.db.Where("user_id = ?", userID).First(&masterAccount).Error; err == nil {
			userAccountBalance = masterAccount.Balance.InexactFloat64()
		}
	case 5: // 子账号
		var subAccount models.SubAccount
		if err := c.db.Where("user_id = ?", userID).First(&subAccount).Error; err == nil {
			userAccountBalance = subAccount.Balance.InexactFloat64()
		}
	case 2: // 普通用户
		// 对于普通用户，尝试获取 HlPay 账户余额
		var userMatrixAccount models.UserMatrixAccount
		if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount).Error; err == nil {
			var hlpayAccount models.HlPayAccountBalance
			if err := c.db.Where("owner_no = ?", userMatrixAccount.MatrixAccount).First(&hlpayAccount).Error; err == nil {
				userAccountBalance = hlpayAccount.RealTimeBalance.InexactFloat64()
			}
		}
	}

	// 统计卡片状态和转账金额
	for _, card := range authorizedCards {
		// 统计各状态卡片数量 - 使用统一状态进行统计
		switch strings.ToLower(card.Status) {
		case "normal":
			stats.ActiveCards++
		case "frozen":
			stats.FrozenCards++
		}
		// 计算总转账金额
		transferAmount, _ := strconv.ParseFloat(card.TotalTransferAmount, 64)
		stats.TotalTransferAmount += transferAmount
	}

	// 设置用户账户余额
	stats.UserAccountBalance = userAccountBalance

	// 计算累计消费（总转账金额 - 总余额），使用decimal确保精度
	transferAmountDecimal := decimal.NewFromFloat(stats.TotalTransferAmount)
	balanceDecimal := decimal.NewFromFloat(stats.TotalBalance)
	consumptionDecimal := transferAmountDecimal.Sub(balanceDecimal)

	// 将结果转换回float64，保留2位小数
	stats.TotalConsumption = consumptionDecimal.Round(2).InexactFloat64()

	fmt.Printf("[calculateHlPayStatisticsFromAuthorizedCards] 统计结果: 总卡数=%d, 活跃卡=%d, 冻结卡=%d, 总余额=%.2f, 总转账=%.2f, 累计消费=%.2f, 用户账户余额=%.2f\n",
		stats.TotalCards, stats.ActiveCards, stats.FrozenCards, stats.TotalBalance, stats.TotalTransferAmount, stats.TotalConsumption, stats.UserAccountBalance)

	return stats, nil
}

// GetCardStatistics 获取卡片统计信息（不写HTTP响应，供聚合接口调用）
func (c *CardListController) GetCardStatistics(ctx *gin.Context) (string, *service.SimplifiedCardStatistics, error) {
	// 获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		return "", nil, fmt.Errorf("platform_info_not_found")
	}

	var userID int64
	if claims, exists := ctx.Get("claims"); exists {
		if authClaims, ok := claims.(*auth.Claims); ok {
			userID = authClaims.UserID
		}
	}
	if userID == 0 {
		return platformInfo.PlatformType, nil, fmt.Errorf("user_not_found")
	}

	switch platformInfo.PlatformType {
	case "hlpay":
		// 查询用户卡
		c.mu.RLock()
		var userCards []models.UserCard
		err := c.db.Where("user_id = ? AND platform = ?", userID, "hlPay").Find(&userCards).Error
		c.mu.RUnlock()
		if err != nil {
			return "hlpay", nil, err
		}

		// 获取过滤参数，与GetCardList保持一致
		cardNo := ctx.Query("cardNo")
		name := ctx.Query("name")
		unifiedStatus := ctx.Query("cardStatus")
		platformStatus := c.mapUnifiedStatusToPlatformStatus("hlpay", unifiedStatus)

		params := &hlpaymodels.CardListRequest{
			CardNo: cardNo,
			Name:   name,
			Status: platformStatus,
		}
		allResult, err := hlservices.GetCardList(ctx.Request.Context(), c.hlpayClient, 1, 1000, params)
		if err != nil {
			return "hlpay", nil, err
		}

		// 过滤出用户有权限的卡，并合并本地转账金额
		userCardIDMap := make(map[string]bool)
		userCardInfoMap := make(map[string]models.UserCard)
		for _, userCard := range userCards {
			userCardIDMap[userCard.CardID] = true
			userCardInfoMap[userCard.CardID] = userCard
		}
		var authorizedRows []hlpaymodels.CardItem
		var totalBalance float64
		for _, card := range allResult.Rows {
			if userCardIDMap[card.ID] {
				// 合并本地 user_cards 的转账金额
				if userCard, ok := userCardInfoMap[card.ID]; ok {
					card.TotalTransferAmount = userCard.TotalTransferAmount.String()
				}
				authorizedRows = append(authorizedRows, card)
				balance, _ := strconv.ParseFloat(card.ActualBalance, 64)
				totalBalance += balance
			}
		}

		// 获取用户角色
		var roleID int64 = 2
		if claims, exists := ctx.Get("claims"); exists {
			if authClaims, ok := claims.(*auth.Claims); ok {
				roleID = authClaims.RoleID
			}
		}

		stats, err := c.calculateHlPayStatisticsFromAuthorizedCards(authorizedRows, totalBalance, userID, roleID)
		if err != nil {
			return "hlpay", nil, err
		}
		return "hlpay", stats, nil

	case "photonpay":
		// 查询用户卡
		c.mu.RLock()
		var userCards []models.UserCard
		err := c.db.Where("user_id = ? AND platform = ?", userID, "photonpay").Find(&userCards).Error
		c.mu.RUnlock()
		if err != nil {
			return "photonpay", nil, err
		}

		// 获取过滤参数，与GetCardList保持一致
		cardBin := ctx.Query("cardBin")
		createdAtStart := ctx.Query("createdAtStart")
		createdAtEnd := ctx.Query("createdAtEnd")
		cardType := ctx.Query("cardType")
		cardFormFactor := ctx.Query("cardFormFactor")
		unifiedStatus := ctx.Query("cardStatus")
		platformStatus := c.mapUnifiedStatusToPlatformStatus("photonpay", unifiedStatus)

		// 获取matrixAccount
		var matrixAccount string
		var userMatrixAccount models.UserMatrixAccount
		if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount).Error; err == nil {
			matrixAccount = userMatrixAccount.MatrixAccount
		}

		// 统计总余额和总转账金额
		var totalBalance float64
		var totalTransferAmount float64
		userCardIDMap := make(map[string]bool)
		userCardInfoMap := make(map[string]models.UserCard)
		for _, userCard := range userCards {
			userCardIDMap[userCard.CardID] = true
			userCardInfoMap[userCard.CardID] = userCard
		}
		params := photonmodels.CardListQueryParams{
			PageIndex:      1,
			PageSize:       1000,
			MatrixAccount:  matrixAccount,
			CardBin:        cardBin,
			CreatedAtStart: createdAtStart,
			CreatedAtEnd:   createdAtEnd,
			CardType:       cardType,
			CardFormFactor: cardFormFactor,
			CardStatus:     platformStatus,
		}
		allResult, err := photonpayServices.GetCardList(ctx.Request.Context(), c.photonpayClient, params)
		if err != nil {
			return "photonpay", nil, err
		}
		for _, card := range allResult.Data {
			if userCardIDMap[card.CardID] {
				if userCard, ok := userCardInfoMap[card.CardID]; ok {
					card.TotalTransferAmount = userCard.TotalTransferAmount.InexactFloat64()
				}
				totalBalance += card.CardBalance
				totalTransferAmount += card.TotalTransferAmount
			}
		}
		// 获取用户角色
		var roleID int64 = 2
		if claims, exists := ctx.Get("claims"); exists {
			if authClaims, ok := claims.(*auth.Claims); ok {
				roleID = authClaims.RoleID
			}
		}
		// 直接调用service层统计，保证和卡列表一致
		stats, err := c.statisticsService.GetSimplifiedCardStatisticsWithBalance(ctx, platformInfo, totalBalance, totalTransferAmount, userID, roleID)
		if err != nil {
			return "photonpay", nil, err
		}
		return "photonpay", stats, nil
	}

	return platformInfo.PlatformType, nil, fmt.Errorf("unsupported_platform")
}
